package com.tobby.camel.camelinaction.chapter3.order;

import static org.junit.Assert.*;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.dataformat.BindyType;
import org.junit.Test;

public class PurchaseOrderUnmarshalBindyTest {

	@Test
	public void testCsv() throws Exception {
		CamelContext context = new DefaultCamelContext();
		context.addRoutes(createRoute());
		context.start();

		MockEndpoint endpoint = context.getEndpoint("mock:result", MockEndpoint.class);
		endpoint.expectedMessageCount(1);
		endpoint.message(0).body().isInstanceOf(BindyOrder.class);

		ProducerTemplate template = context.createProducerTemplate();
		template.sendBody("direct:toObject", "Camel in Action,34.6,1\n");

		endpoint.assertIsSatisfied();

		// bindy now turned that into a list of rows so we need to grab the order from the
		// list
		// List rows = endpoint.getReceivedExchanges().get(0).getIn().getBody(List.class);
		// each row is a map with the class name as the index
		// Map row = (Map)rows.get(0);
		// get the order from the map
		// BindyOrder order = (BindyOrder)row.get(BindyOrder.class.getName());
		BindyOrder order = (BindyOrder) endpoint.getReceivedExchanges().get(0).getIn()
				.getBody(BindyOrder.class);
		assertNotNull(order);

		// assert the order contains the expected data
		assertEquals("Camel in Action", order.getName());
		assertEquals("34.60", order.getPrice().toString());
		assertEquals(1, order.getAmount());
	}

	private RouteBuilder createRoute() {
		return new RouteBuilder() {

			@Override
			public void configure() throws Exception {
				from("direct:toObject").unmarshal().bindy(BindyType.Csv, BindyOrder.class)
						.to("mock:result");
			}
		};
	}

}
